package xyz.hlh.boot3.aspect.simple;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * @author HLH
 * @description 简单的测试
 * @email 17703595860@163.com
 * @date Created in 2021/8/7 上午11:25
 */
//@Component // 注册组件
//@Aspect // 开启aop
public class MyAspect {

    /**
     * 匹配所有service中的所有方法
     */
    @Pointcut(value = "execution(public * xyz.hlh.boot3..service..*(..))")
    public void pointCut() {}

    @Before(value = "pointCut()")
    public void before(JoinPoint joinPoint) {
        System.out.println("前置通知");
    }

    @AfterReturning(value = "pointCut()", returning = "returnObj")
    public void afterReturning(JoinPoint joinPoint, Object returnObj) {
        System.out.println("后置通知");
    }

    @AfterThrowing(value = "pointCut()", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Exception e) {
        System.out.println("异常通知");
    }

    @After(value = "pointCut()")
    public void afterThrowing(JoinPoint joinPoint) {
        System.out.println("最终通知");
    }

    /**
     * 环绕通知因为包含显示的方法调用，所以必须要有返回参数
     *  因为显示调用，处理异常，所以和上面的四个通知只能选择一种使用
     */
    @Around(value = "pointCut()")
    public Object around(ProceedingJoinPoint pjp) {
        Object result = null;
        try {
            System.out.println("前置处理");
            // 调用方法
            result = pjp.proceed(pjp.getArgs());
            System.out.println("后置处理");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("异常处理");
        } finally {
            System.out.println("最终处理");
        }
        return result;
    }

}
